﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.MasterData
{
    public partial class FieldInteractionEditor : Form, IComponentEditor
    {
        private object _ActivityNode;
        private FieldInteractionComponent _InteractionComponent;

        public FieldInteractionEditor()
        {
            InitializeComponent();
        }

        private void FieldDependencyEditor_Load(object sender, EventArgs e)
        {

        }

        #region Implementation of IComponentEditor

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        /// <summary></summary>
        public object OwnerActivityNode
        {
            get
            {
                return _ActivityNode;
            }
            set
            {
                _ActivityNode = value;
            }
        }

        /// <summary></summary>
        public Type WorkflowComponentType
        {
            get
            {
                return typeof(FieldInteractionComponent);
            }
        }

        /// <summary></summary>
        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents, object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ActivityNode = activityNode;
            this._InteractionComponent = (FieldInteractionComponent)wfComponent;

            FieldInteractionInstruction instruction =
                (FieldInteractionInstruction)this._InteractionComponent.Instruction;

            this.txt_ConnStr.Text = instruction.ConnStr;
            this.txt_Schema.Text = instruction.SchemaName;
            this.PopulateTables();
            this.SelectComboxItem(this.cbo_Tables, instruction.TblName);
            this.rt_Sql.Text = instruction.Sql;
            this.PopulateTableFields();
            this.SelectComboxItem(this.cbo_DeterminantField, instruction.DeterminantField);
            for(int i=0;i<this.clb_DependentFields.Items.Count;i++)
            {
                if(instruction.DependentFields !=null && instruction.DependentFields.Contains(this.clb_DependentFields.Items[i].ToString()))
                    this.clb_DependentFields.SetItemChecked(i,true);
                else 
                    this.clb_DependentFields.SetItemChecked(i,false);
            }
            this.txt_OutputFilePath.Text = instruction.OutputFilePath;
        }

        /// <summary></summary>
        public void SaveSettings()
        {
            FieldInteractionInstruction instruction =
               (FieldInteractionInstruction)this._InteractionComponent.Instruction;

            instruction.ConnStr = this.txt_ConnStr.Text;
            instruction.SchemaName = this.txt_Schema.Text;
            instruction.TblName = this.cbo_Tables.Text;
            instruction.Sql = this.rt_Sql.Text;
            instruction.DeterminantField = this.cbo_DeterminantField.Text;
            instruction.OutputFilePath = this.txt_OutputFilePath.Text;
            instruction.DependentFields = new List<string>();
            for (int i = 0; i < this.clb_DependentFields.Items.Count; i++)
            {
                if(this.clb_DependentFields.GetItemChecked(i))
                {
                    instruction.DependentFields.Add(this.clb_DependentFields.Items[i].ToString());
                }
            }

            this._InteractionComponent.Instruction = instruction;
        }

        /// <summary></summary>
        public TestResult Test()
        {
            throw new System.NotImplementedException();
        }

        #endregion

        private void cbo_Tables_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.PopulateTableFields();
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            this.PopulateTableFields();
        }

        private void PopulateTableFields()
        {
            if (!string.IsNullOrEmpty(this.txt_ConnStr.Text) && this.cbo_Tables.SelectedIndex >= 0)
            {
                TableColumn[] cols = null;
                if (string.IsNullOrEmpty(this.rt_Sql.Text))
                {
                    cols = DbUtil.GetTableColumns(
                        DataProviderType.MSSQL, this.txt_ConnStr.Text,
                        this.txt_Schema.Text, this.cbo_Tables.Text);
                }
                else
                {
                    cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, this.txt_ConnStr.Text, this.rt_Sql.Text);
                }
                this.cbo_DeterminantField.Items.Clear();
                this.clb_DependentFields.Items.Clear();
                if (cols != null && cols.Length > 0)
                {
                    foreach (TableColumn col in cols)
                    {
                        if (FieldDataType.IsNumber(col.DbType))
                        {
                            this.cbo_DeterminantField.Items.Add(col.ColumnName);
                            this.clb_DependentFields.Items.Add(col.ColumnName);
                        }
                    }
                }
            }
        }

        private void btn_SelectAll_Click(object sender, EventArgs e)
        {
            if(this.clb_DependentFields.Items.Count>0)
            {
                for(int i=0;i<this.clb_DependentFields.Items.Count;i++)
                {
                    this.clb_DependentFields.SetItemChecked(i, !(this.clb_DependentFields.GetItemChecked(i)));
                }
            }
        }

        private void btn_RefreshTbls_Click(object sender, EventArgs e)
        {
            this.PopulateTables();
        }

        private void PopulateTables()
        {
            if (!string.IsNullOrEmpty(this.txt_ConnStr.Text))
            {
                string schemaName = "dbo";
                if (!string.IsNullOrEmpty(this.txt_Schema.Text))
                    schemaName = this.txt_Schema.Text;
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, schemaName, this.txt_ConnStr.Text);
                this.cbo_Tables.Items.Clear();
                if (tblNames != null && tblNames.Length > 0)
                {
                    foreach (string tblName in tblNames)
                        this.cbo_Tables.Items.Add(tblName);
                }
            }
        }

        private void SelectComboxItem(ComboBox comboBox, string value)
        {
            if(comboBox.Items.Count>0 && !string.IsNullOrEmpty(value))
            {
                for(int i=0;i<comboBox.Items.Count;i++)
                {
                    if(comboBox.Items[i].ToString()==value)
                    {
                        comboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
        }

        private void btn_SaveAs_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Profile files(*.xml)|*.xml";
            if (dlg.ShowDialog() == DialogResult.OK)
                this.txt_OutputFilePath.Text = dlg.FileName;
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if(this.UpdateComponentSettingEvent !=null)
                this.UpdateComponentSettingEvent(this._ActivityNode,this._InteractionComponent);
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_OpenResult_Click(object sender, EventArgs e)
        {
            FieldInteractionViewer viewer=new FieldInteractionViewer();
            viewer.ShowDialog();
        }
    }
}
